package net.zoneland.zrdp.framework.web.service;

import net.zoneland.zrdp.common.config.ZonevueConfig;
import net.zoneland.zrdp.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.common.core.domain.model.LoginUser;
import net.zoneland.zrdp.common.enums.UserStatus;
import net.zoneland.zrdp.common.exception.ServiceException;
import net.zoneland.zrdp.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 用户验证处理
 *
 * @author zonevue
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private ISysUserService userService;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ZonevueConfig zonevueConfig;

    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        final SysUser user = userService.selectUserByUserName(username);
        // 如果是sso 登陆 不需要进行密码验证。
        if (!zonevueConfig.isSsoEnabled()) {
            if (Objects.isNull(user)) {
                LOGGER.info("登录用户：{} 不存在.", username);
                throw new ServiceException("登录用户：" + username + " 不存在");
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                LOGGER.info("登录用户：{} 已被删除.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                LOGGER.info("登录用户：{} 已被停用.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已停用");
            }
            passwordService.validate(user);
        } else {
            // 如果是单点登录，设置用户的验证密码为sso
            user.setPassword(SecurityUtils.encryptPassword("sso"));
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(final SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
